import common from "../../lib/common/common.js";
﻿import plugin from '../../lib/plugins/plugin.js'
import moment from 'moment'
import fetch from "node-fetch";
import fs from 'fs'
import yaml from "yaml"
import sharp from 'sharp'
import pLimit from 'p-limit'

let sizenum = 10
let proxy = 'i.yuki.sh' 
let maxnum = 30  //并发限制

let cooldowns = new Map();
let NumReg = '[一壹二两三四五六七八九十百千万亿\\d]+'
export class lolicon extends plugin {
    constructor() {
        super({
            /** 功能名称 */
            name: "lolicon",
            /** 功能描述 */
            dsc: "lolicon",
            /** https://oicqjs.github.io/oicq/#events */
            event: "message",
            /** 优先级，数字越小等级越高 */
            priority: 50000,
            rule: [
				{
                    reg: '^#(.*)(涩|涩|铯|瑟|瑟|色)(图|涩|涩|铯|瑟|瑟|色)(.*)$',
                    fnc: 'setu'
                },
				{
                    reg: '^#an搜索(.*)$',
                    fnc: 'anosu'
                }
			]
        });
    }

  
  async setu(e) {
	if (!e.isGroup) {
		return
	}
	let groupId = e.group_id
    let cfg = await loadcfg(groupId)
	if (!cfg && !e.isMaster) return
	
    if (!cfg.setu && !e.isMaster) {
	     logger.mark(`${groupId} 涩图权限 ${cfg.setu}`)
         return;
    }
	if (!e.isMaster ) {
	    let cooldown = cooldowns[groupId];
	    if (cooldown && cooldown > Date.now()) {
            let remainingTime = Math.ceil((cooldown - Date.now()) / 1000);
            e.reply(`lsp注意身体，请${remainingTime}秒后再来～`,true,{ recallMsg: 5 });
            return;
        }
	}	
	
    let msg = e.msg.replace(/#|(涩|涩|铯|瑟|瑟|色)(图|涩|涩|铯|瑟|瑟|色)/g, '').trim()
        msg = msg.replace('r18', '');

    let stringlist = msg.split(/[,， ]+/);
    let tag = stringlist[0]
    let key = stringlist[1]
    if (!tag) {
        tag = "";
    }
    if (!key) {
        key = "";
    }
    let num = 1
    let Match = e.msg.match(new RegExp(`(${NumReg})(张|份)`));
    if (Match) {
        num = Number(Match[1]);
        if (isNaN(num)) {
            return;
        }
        tag = tag.replace(Match[0], "").trim();  // 去掉匹配的页码部分
    }
    if (num > 20){
	    num = 20
	}	

    let size = num > sizenum ? 'regular' : 'original'

	let r18 = 0
	if (cfg.r18 && e.msg.includes('r18')) {
	    r18 = 1
	}
	
	let response = ""
	let res = ""
	
    let url = `https://api.lolicon.app/setu/v2?excludeAI=false&tag=${tag}&tag=${key}&proxy=${proxy}&r18=${r18}&size=${size}&num=${num}`;
    try{
        response = await fetch(url);
        res = await response.json();
	} catch (error) {
		e.reply('请求失败',true,{ recallMsg: 5 })
		return
	}
    if (res.error) {
		e.reply(res.error)
		return
	}	
	if (res.data.length == 0) {
        e.reply(`没有搜到${tag}${key}`,true,{ recallMsg: 5 });
        return;
    }
	
	// 只有在请求成功时才设置CD
    if (!e.isMaster) {
        cooldowns[groupId] = Date.now() + cfg.cd * 1000;
    }
    
    let msgs = [];
	if (cfg.r18 && res.data.length > 2) {
	    e.reply(`lolicon 开始执行r8任务${tag}${key}，数量 ${res.data.length}`,false,{ recallMsg: 5 })
	} else if (res.data.length > 2){
        e.reply(`lolicon 开始执行任务${tag}${key}，数量 ${res.data.length}`,false,{ recallMsg: 5 })
    }

	msgs.push(`tag`)
	// 设置并发限制
    const limit = pLimit(maxnum)
	    // 使用 Promise.all 和 p-limit 并行下载图片
        await Promise.all(res.data.map((k, index) => limit(async () => {
			let ai = k.aiType == 2 ? '（ai绘图）' : ''
			let imageData = ''
            try {
                let image = await fetch(k.urls[size]);
                    imageData = Buffer.from(await image.arrayBuffer());
                let flippedImage = await sharp(imageData).flop().toBuffer();
		        msgs.push([
                    `【标题】${k.title}\n`,
			        `【日期】${moment(new Date(k.uploadDate)).format('YYYY-MM-DD HH:mm:ss')}\n`,
			        `【画师】${k.author}\n`,
					`【pid】${k.pid}${ai}`,
			        segment.image(flippedImage)
                  ])
                logger.info(`${tag}${key} 图片${index+1}处理 ok`);
            } catch (error) {
				if (imageData.length < 10240) { 
                    msgs.push([
                        `【标题】${k.title}\n`,
			            `【日期】${moment(new Date(k.uploadDate)).format('YYYY-MM-DD HH:mm:ss')}\n`,
                        `【画师】${k.author}\n`,
					    `【pid】${k.pid}${ai}\n`,
			            `【tags】${k.tags}\n`,
			            `【404】传送门：https://www.pixiv.net/artworks/${k.pid}`
                    ])
                    logger.error(`${tag}${key} 图片${index+1} 404错误`);
                } else {
			    	msgs.push([
                        `【标题】${k.title}\n`,
			            `【日期】${moment(new Date(k.uploadDate)).format('YYYY-MM-DD HH:mm:ss')}\n`,
                        `【画师】${k.author}\n`,
					    `【pid】${k.pid}${ai}`,
			            segment.image(k.urls[size])
                    ])
                    logger.error(`${tag}${key} 图片${index+1}处理 failed`);
				}
            }
        })));
    
   msgs[0] = `tag: ${tag}${key}，num: ${res.data.length}，r18: ${r18 == 1}\n图片质量: ${size}`

	let ForwardMsg = await common.makeForwardMsg(e,msgs)	  
        await e.reply(ForwardMsg,false,{ recallMsg: num > 5 ? cfg.recall : 60 })
         
    return true		
  }	
  
  async anosu(e) {
	if (!e.isGroup) {
		return
	}
    let groupId = e.group_id
    let cfg = await loadcfg(groupId)
	if (!cfg && !e.isMaster) return
	
    if (!cfg.setu && !e.isMaster) {
	     logger.mark(`${groupId} 涩图权限 ${cfg.setu}`)
         return;
    }
	if (!e.isMaster ) {
	    let cooldown = cooldowns[groupId];
	    if (cooldown && cooldown > Date.now()) {
            let remainingTime = Math.ceil((cooldown - Date.now()) / 1000);
            e.reply(`lsp注意身体，请${remainingTime}秒后再来～`,true,{ recallMsg: 5 });
            return;
        }
	}	
	
    let msg = e.msg.replace(/#|an搜索/g, '').trim()
    if (msg.includes('r18')) {
        msg = msg.replace('r18', '');
    }
   
    let num = 1
    let Match = e.msg.match(new RegExp(`(${NumReg})(张|份)`));
    if (Match) {
        num = Number(Match[1]);
        if (isNaN(num)) {
            return;
        }
        msg = msg.replace(Match[0], "").trim();  // 去掉匹配的页码部分
    }
    if (num > 30){
	    num = 20
	}	
	
	let size = num > sizenum ? 'regular' : 'original'
	
	let r18 = 0
	if (cfg.r18 && e.msg.includes('r18')) {
	    r18 = 1
	}
	
	let response = ""
	let res = ""
	
    let url = `https://image.anosu.top/pixiv/json?db=0&keyword=${msg}&proxy=${proxy}&r18=${r18}&size=${size}&num=${num}`;
    try{
        response = await fetch(url);
        res = await response.json();
	} catch (error) {
		e.reply('请求失败',true,{ recallMsg: 5 })
		return
	}
   
	if (res.length == 0) {
        e.reply(`没有搜到${msg}`,true,{ recallMsg: 5 });
        return;
    }
	// 只有在请求成功时才设置CD
    if (!e.isMaster) {
        cooldowns[groupId] = Date.now() + cfg.cd * 1000;
    }
    
    let msgs = [];
	if (cfg.r18 && res.length > 2) {
	    e.reply(`anosu 开始执行r8任务${msg}，数量 ${res.length}`,false,{ recallMsg: 5 })
	} else if (res.length > 2){
        e.reply(`anosu 开始执行任务${msg}，数量 ${res.length}`,false,{ recallMsg: 5 })
    }

	msgs.push(`msg`)
    // 设置并发限制
    const limit = pLimit(maxnum)
	    // 使用 Promise.all 和 p-limit 并行下载图片
        await Promise.all(res.map((k, index) => limit(async () => {
			let imageData = ''
            try {
                let image = await fetch(k.url);
                    imageData = Buffer.from(await image.arrayBuffer());
                let flippedImage = await sharp(imageData).flop().toBuffer();
		        msgs.push([
                    `【标题】${k.title}\n`,
			        `【画师】${k.user}\n`,
					`【pid】${k.pid}`,
			        segment.image(flippedImage)
                  ])
                logger.info(`${msg} 图片${index+1}处理 ok`);
            } catch (error) {
				if (imageData.length < 10240) { 
                    msgs.push([
                        `【标题】${k.title}\n`,
			            `【画师】${k.user}\n`,
					    `【pid】${k.pid}\n`,
			            `【tags】${k.tags}\n`,
			            `【404】传送门：https://www.pixiv.net/artworks/${k.pid}`
                    ])
                    logger.error(`${msg} 图片${index+1} 404错误`);
                } else {
			    	msgs.push([
                        `【标题】${k.title}\n`,
			            `【画师】${k.user}\n`,
					    `【pid】${k.pid}`,
			            segment.image(k.url)
                    ])
                    logger.error(`${msg} 图片${index+1}处理 failed`);
				}
            }
        })));

    msgs[0] = `keyword: ${msg}，num: ${res.length}，r18: ${r18 == 1}\n图片质量: ${size}`

	let ForwardMsg = await common.makeForwardMsg(e,msgs)	  
        await e.reply(ForwardMsg,false,{ recallMsg: num > 5 ? cfg.recall : 60 })
         
    return true		
  }	
 
}

async function loadcfg(id) {
	let file = `data/pixiv.yaml`
    if (!fs.existsSync(file)) return false
	
    let data = yaml.parse(fs.readFileSync(file, 'utf8'))
	if (!data[id]) return false
	
	return data[id]
}

	






